<style lang="scss" scoped>
    @import "../../utils/base.scss";
</style>

<template>
    <div ref='base' class="quest_content" style="overflow-y:auto" >
        <template id="baseInfo">
            <div class="qheader" :style="{borderBottom: ifedit ? '0px solid rgb(210,210,210)' : '1px solid rgb(210,210,210)',}">
                <p>提单人信息</p>
            </div>
            <div class="gcontent">
                <Form :model="object.user" :label-width="140" label-position="left" class="form form_left" >
                    <Row v-if="reqId != null && reqId != ''">
                        <Col span="8" >
                            <FormItem label="工单ID:" >
                                <Input v-model="reqId"  :readonly="true" />
                            </FormItem>
                        </Col>
                    </Row>
                    <Row >
                        <Col span="8" >
                            <FormItem label="申请人姓名:" >
                                <Input v-model="object.user.user_name"  :readonly="true" />
                            </FormItem>
                        </Col>
                        <Col span="8" class="col_left">
                            <FormItem label="申请人单位:"  >
                                <Input v-model="object.user.department" :readonly="true" />
                            </FormItem>
                        </Col>
                    </Row>
                </Form>
            </div>
        </template>

        <template id="projectInfo">
            <div class="qheader" :style="{borderBottom: ifedit ? '0px solid rgb(210,210,210)' : '1px solid rgb(210,210,210)',}">
                <p>项目信息</p>
            </div>
            <div class="gcontent">
                <Form ref="projectInfo" :model="object.project" :label-width="140" label-position="left" class="form form_left" :rules="projectRules">
                    <Row>
                        <Col span="8">
                            <FormItem label="工单标题:" prop="reqSubject">
                                <Input  v-model="object.reqSubject" :readonly="ifedit" placeholder="XX租户申请XX非实名制账号"/>
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span="8">
                            <FormItem label="提单租户:" prop="roleId">
                                <Input v-if="ifedit" v-model="object.role.tenant_name" :readonly="true" />
                                <Select v-else filterable v-model="object.roleId" :label-in-value="true" @on-change="selectTenant" :disabled="ifedit" placeholder="请选择所属租户">
                                    <Option v-for="(i,index) in tenantList" :value="i.id" :key="index">{{i.tenant_name}}</Option>
                                </Select>
                            </FormItem>
                        </Col>
                        <Col span="8" class="col_left">
                            <FormItem label="所属项目:" prop="projectId">
                                <Input v-if="ifedit" v-model="object.project.project" :readonly="true" />
                                <Select v-else filterable v-model="object.projectId" @on-change="getProjectInfo" :disabled="ifedit" placeholder="请选择所属项目">
                                     <Option v-for="(item,index) in projectList" :value="item.id" :key="index">{{item.project}}</Option>
                                </Select>
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span="8">
                            <FormItem label="运营人员:" >
                                <Input v-if="object.project.business!=null && object.project.business!=undefined && object.project.business!=''" v-model="object.project.business" :readonly="true"/>
                                <Input v-else v-model="object.project.tenant_business" :readonly="true"/>
                            </FormItem>
                        </Col>
                        <Col span="8" class="col_left">
                            <FormItem label="项目类型:">
                                <Input v-model="object.project.projectType" :readonly="true" />
                            </FormItem>
                        </Col>
                    </Row>
                    <Row >
                        <Col span="8" >
                            <FormItem label="项目经理:">
                                <Input v-model="object.project.manager" :readonly="true" />
                            </FormItem>
                        </Col>
                        <Col span="8" class="col_left">
                            <FormItem label="经理联系方式:">
                                <Input v-model="object.project.manager_phone" :readonly="true"/>
                            </FormItem>
                        </Col>
                    </Row>
                </Form>
            </div>
        </template>

        <template id="noRealName">
            <div class="qheader" :style="{borderBottom: ifedit ? '0px solid rgb(210,210,210)' : '1px solid rgb(210,210,210)',}">
                <p>非实名制账号信息</p>
            </div>
            <div class="gcontent">
            	<Form ref="noRealName" :model="object.object" :label-width="160" label-position="left" class="form form_left" :rules="objectRules">
                    <Row>
                        <Col span="8">
                            <FormItem label="所属系统:" prop="sysId">
                                <Input v-if="ifedit" v-model="object.object.sysName" :readonly="true" />
                                <Select v-else filterable v-model="object.object.sysId" @on-change="selectSys" :label-in-value="true" placeholder="请选择所属系统">
                                     <Option v-for="(item,index) in sysList" :value="item.id" :key="index">{{item.sysName}}</Option>
                                </Select>
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span="8">
                            <FormItem label="报备审批起始日期:" prop="useStartTime">
                                <Input v-if="ifedit" v-model="object.object.useStartDate" :readonly="true" />
                                 <DatePicker v-else v-model="object.object.useStartDate" type="date" placeholder="请选择报备审批起始日期" style="width: 100%" @on-change="selectStartTime"></DatePicker>
                            </FormItem>
                        </Col>
			            <Col span="8" class="col_left">
			              <FormItem prop="useEndTime">
			                <template slot="label">
			                  <span>报备审批结束日期</span>
			                  <Tooltip content="最长不超过5个自然日" max-width="200" placement="right" :transfer="true" style="white-space: normal;">
			                    <Icon type="md-help-circle" />
			                  </Tooltip>
			                  <span>:</span>
			                </template>
			                <Input v-if="ifedit" v-model="object.object.useEndDate" :readonly="true" />
			                <DatePicker v-else v-model="object.object.useEndDate" type="date" placeholder="请选择报备审批结束日期" style="width: 100%" @on-change="selectEndTime"></DatePicker>
			              </FormItem>
			            </Col>
                    </Row>
                    <Row>
                        <Col span="8">
                            <FormItem label="本端所属IP(段):" prop="localIp">
<!--                                 <template slot="label">
                                    <span>本端所属IP(段)</span>
                                    <Tooltip content="申请多个IP请以英文逗号分隔" max-width="200" placement="right" :transfer="true" style="white-space: normal;">
                                        <Icon type="md-help-circle" />
                                    </Tooltip>
                                    <span>:</span>
                                </template> -->
                                <Tooltip content="申请多个IP请以英文逗号分隔" max-width="220" placement="top-start" :transfer="true" style="white-space: normal;width:100%">
                                    <Input v-model="object.object.localIp" :readonly="ifedit" type="textarea"/>
                                </Tooltip>
                            </FormItem>
                        </Col>
                        <Col span="8" class="col_left">
                            <FormItem label="对端所属IP(段):" prop="targetIp">
                                <!-- <template slot="label">
                                    <span>对端所属IP(段)</span>
                                    <Tooltip content="申请多个IP请以英文逗号分隔" max-width="200" placement="right" :transfer="true" style="white-space: normal;">
                                        <Icon type="md-help-circle" />
                                    </Tooltip>
                                    <span>:</span>
                                </template> -->
                                <Tooltip content="申请多个IP请以英文逗号分隔" max-width="220" placement="top-start" :transfer="true" style="white-space: normal;width:100%">
                                    <Input v-model="object.object.targetIp" :readonly="ifedit" type="textarea"/>
                                </Tooltip>
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span="8">
                            <FormItem label="非实名制账号名:" prop="account">
                                <Input v-model="object.object.account" :readonly="ifedit" />
                            </FormItem>
                        </Col>
                        <Col span="8" class="col_left">
                            <FormItem label="使用人4A账号:" prop="user4aAccount">
                                <Input v-model="object.object.user4aAccount" placeholder="可一起填写多个使用人4A账号" :readonly="ifedit" />
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span="24" style="width:97%">
                            <FormItem label="涉及的操作指令:" prop="operation">
                                <Input v-model="object.object.operation" type="textarea" :rows="3" placeholder="su、ssh、ftp、telnet、sftp等命令" :readonly="ifedit" />
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span="24" style="width:97%">
                            <FormItem label="使用原因及需求:">
                                <Input v-model="object.reqDes" type="textarea" :rows="3" placeholder="必须详细描述，否则视为违规" :readonly="ifedit" />
                            </FormItem>
                        </Col>
                    </Row>
<!--                     <Row>
                        <Col span="24" style="width:97%">
                            <FormItem label="备注:" prop="des">
                                <Input v-model="object.des" type="textarea" rows="3" :readonly="ifedit" />
                            </FormItem>
                        </Col>
                    </Row> -->
            	</Form>
            </div>
        </template>

        <!-- 附件 -->
        <template>
            <div class="qheader" :style="{borderBottom: '1px solid rgb(210,210,210)',}">
                <p>附件</p>
            </div>
            <component ref="file" :is="'file'" :ifedit="ifedit" :filesList="filesList" v-model="object.files"></component>
        </template>
    </div>
</template>

<script>
    import ajax from "../../ajax_util"
    import Axios from 'axios'
    import notice from '../../base/notice'
    import file from './settledin/file'
    import fileUpload from '../../base/file_uploader'
    import fileModal from '../../base/file_modal'
    import fileDownload from '../../base/file_download'

 	export default {
    	name: "apply",
        components:{
           notice,file,fileUpload,fileModal,fileDownload
        },
        data (){
            const validateReqSubject = (rule, value, callback) => {
                if (this.object.reqSubject === '') {
                    callback(new Error('填写工单标题'));
                }else{
                  if(this.object.reqSubject.length > 50){
                    callback(new Error('最多填写50个字符'));
                  }else{
                    callback()
                  }
                }
            };
            const validateRoleId = (rule, value, callback) => {
                if (this.object.roleId === undefined || this.object.roleId === null || this.object.roleId < 1) {
                    callback(new Error('请选择租户角色'));
                }else{
                    callback()
                }
            };
            const validateProjectId = (rule, value, callback) => {
                if (this.object.projectId === undefined || this.object.projectId === null || this.object.projectId < 1) {
                    callback(new Error('请选择关联项目'));
                }else{
                    callback()
                }
            };
            const validateSysId = (rule, value, callback) => {
                if (this.object.object.sysId === undefined || this.object.object.sysId === null || this.object.object.sysId < 1) {
                    callback(new Error('请选择所属系统'));
                }else{
                    callback()
                }
            };
            const validateStartTime = (rule, value, callback) => {
                if (this.object.object.useStartTime === undefined || this.object.object.useStartTime === null || this.object.object.useStartTime < 1) {
                    callback(new Error('请选择报备审批起始日期'));
                }else{
                    callback()
                }
            };
            const validateEndTime = (rule, value, callback) => {
                if (this.object.object.useEndTime === undefined || this.object.object.useEndTime === null || this.object.object.useEndTime < 1) {
                    callback(new Error('请选择报备审批结束日期'));
                }else{
                	console.log("0000",this.object.object.useEndTime - this.object.object.useStartTime);
                	if(this.object.object.useStartTime > this.object.object.useEndTime){
                		callback(new Error('起始日期不能大于结束日期'));
                	}else if(this.object.object.useEndTime - this.object.object.useStartTime > 432000){
                		callback(new Error('报备审批日期最长不超过5个自然日'));
                	}else{
                		callback()
                	}
                }
            };
            const validateLocalIp = (rule, value, callback) => {
                if (this.object.object.localIp === undefined || this.object.object.localIp === null || this.object.object.localIp == '') {
                    callback(new Error('请填写本端所属IP(段)'));
                }else{
                    if(!this.checkIP(this.object.object.localIp)){
                        callback(new Error('输入IP格式有误，申请多个IP请以英文逗号分隔'));
                    }else{
                        callback()
                    }
                }
            };
            const validateTargetIp = (rule, value, callback) => {
                if (this.object.object.targetIp === undefined || this.object.object.targetIp === null || this.object.object.targetIp == '') {
                    callback(new Error('请填写对端所属IP(段)'));
                }else{
                    if(!this.checkIP(this.object.object.targetIp)){
                        callback(new Error('输入IP格式有误，申请多个IP请以英文逗号分隔'));
                    }else{
                        callback()
                    }
                }
            };
        	return {
		        disabledDate: {
		          disabledDate(date) {
		            return date && date.valueOf() < Date.now() - 24 * 60 * 60 * 1000;
		          }
		        },
                projectRules:{
                    reqSubject:[
                        {required: true,validator: validateReqSubject, trigger: 'blur'}
                    ],
                    roleId: [
                        {required: true,type: 'number', trigger: 'change',validator: validateRoleId},
                    ],
                    projectId: [
                        {required: true,type: 'number', trigger: 'change',validator: validateProjectId},
                    ]
                },
                objectRules:{
                    sysId: [
                        {required: true,type: 'number', trigger: 'change',validator: validateSysId},
                    ],
                    useStartTime: [
                         { required: true, type: 'date', validator: validateStartTime, trigger: 'change' },
                    ],
                    useEndTime: [
                         { required: true, type: 'date', validator: validateEndTime, trigger: 'change' },
                    ],
                    localIp:[
                        {required: true,validator: validateLocalIp, trigger: 'blur'}
                    ],
                    targetIp:[
                        {required: true,validator: validateTargetIp, trigger: 'blur'}
                    ],
                    account:[
                        {required: true,message: '请填写非实名制账号名', trigger: 'blur'}
                    ],
                    user4aAccount:[
                        {required: true,message: '请填写使用人4A账号', trigger: 'blur'}
                    ],
                    operation:[
                        {required: true,message: '请填写涉及的操作指令', trigger: 'blur'}
                    ],
                    reqDes:[
                        {required: true,message: '请填写使用原因及需求', trigger: 'blur'}
                    ]
                },
        		object:{
        			reqSubject:"",
        			roleId:0,
        			projectId:0,
        			user:{},
        			role:{},
                    reqDes:"",
                    des:"",
					project: {
						create_time: 0,
						cycle: "",
						des: "",
						end_time: 0,
						id: 0,
						isContract: "",
						isWithDraw: 0,
						manager: "",
						manager_phone: "",
						position: "",
						project: "",
						projectType: "",
						tenant_id: 0,
						tenant_name: "",
                        business:"",
                        tenant_business:"",
						withDrawTime: 0
					},
					object:{
                        account: "",
                        id: 0,
                        localIp: "",
                        operatio: "",
                        overId: 0,
                        sysId: 0,
                        sysName: "",
                        targetIp: "",
                        useEndTime: 0,
                        useStartTime: 0,
                        user4aAccount: ""
					},
                    files:[]
        		},
        		tenantList:[],
        		projectList:[],
                tenant:{},
                userId:0,
				sysList:[]
        	}
        },
        mounted:function() {
			if(this.reqId==null && this.draftsId == null){
        		this.getBaseInfo();
        	}else if (this.reqId != null) {
                this.getApplyInfo();
                if(!this.ifedit){
                    this.getTenants(this.userId);
                    this.getSys();
                }
            }else if (this.draftsId != null) {
                this.getDrafts();
            }
        },
        methods: {
            projectValidate(){
                var isSubmit = false
                this.$refs["projectInfo"].validate((valid) => {
                    if (valid) {
                        if(this.object.roleId == undefined || this.object.roleId < 1 || this.object.projectId == undefined || this.object.projectId < 1){
                            this.$Message.error('请填写基本信息');
                        }else{
                            isSubmit = true
                        }
                    } else {
                        this.$Message.error('请填写基本信息');
                    }
                })
                return isSubmit
            },
            objectValidate(){
                var isSubmit = false
                this.$refs["noRealName"].validate((valid) => {
                    if (valid) {
                        if(this.object.object.sysId == undefined || this.object.object.sysId < 1 ){
                            this.$Message.error('账号信息未填写完或格式不对');
                        }else{
                            isSubmit = true
                        }
                    } else {
                        this.$Message.error('账号信息未填写完或格式不对');
                    }
                })
                return isSubmit
            },
            getBaseInfo(){
                this.object.userId = this.$store.state.user.id;
                this.object.user.id = this.$store.state.user.id;
                this.object.user.user_name = this.$store.state.user.user_name;
                this.object.user.department = this.$store.state.user.department;
                this.getTenants(this.object.user.id);
                this.getSys();
                console.log("------getBaseInfo-----------",this.object.user)
            },
            getApplyBaseInfo(){
                this.object.userId = this.processInfo.base.userFBean.id;
                this.object.user.id = this.processInfo.base.userFBean.id;
                this.object.user.user_name = this.processInfo.base.userFBean.user_name;
                this.object.user.department = this.processInfo.dptName;
            },
            getApplyInfo(){
                console.log("getApplyInfo------this.processInfo--->", this.processInfo);
                this.getApplyBaseInfo();

                var data = this.processInfo;
                this.object.object = data.content;
                this.object.object.useStartDate = this.utils.formatDate(new Date(data.content.useStartTime*1000), "yyyy-MM-dd");
                this.object.object.useEndDate = this.utils.formatDate(new Date(data.content.useEndTime*1000), "yyyy-MM-dd");

                this.object.files = data.files;
                this.object.reqSubject = this.processInfo.reqSubject;
                this.object.reqDes = data.reqDes;
                this.object.des = data.des;

                this.object.projectId = this.processInfo.base.project.id;
                this.object.project = this.processInfo.base.project;
                this.object.roleId = this.processInfo.base.role.id;
                this.object.role = this.processInfo.base.role;
                this.tenant.value = this.processInfo.base.role.id;
                this.tenant.label = this.processInfo.base.role.tenant_name;

                this.userId = this.processInfo.base.userFBean.id;
            },
            getDrafts(){
                var url = this.CONFIG.base_url_test + "/draft/content/" + this.draftsId;
                var that = this;
                ajax.get({
                  url: url,
                  that: that,
                  params: null,
                  success: function(data) {
                    console.log("-----getDrafts-----",data);
                    that.object = data.req;
                    console.log("-----22222-----",that.object);
                    that.getTenants(that.object.userId);
                    that.getSys();
                  }
                })
            },
        	getTenants(userId){
                var url = this.CONFIG.url_know + "/tenantByUserId/" + userId;
                var that=this;
                ajax.get({
                    url: url,
                    that: that,
                    params: null,
                    success:function(data){
                    	console.log("------55555-----------",data)
                        that.tenantList = data;

                        if(that.object.role.id != null && that.object.role.id != undefined && that.object.role.id > 0){
                            var tenant = {};
                            tenant.value = that.object.role.id;
                            tenant.label = that.object.role.tenant_name;
                            that.selectTenant(tenant);
                        }
                    }
                })
        	},
        	selectTenant(tenant){
        		console.log("---------tenant-----",tenant)
        		this.object.role.id = tenant.value;
        		this.object.role.tenant_name = tenant.label;

        		//this.object.project = {};
                this.tenantList.some(item =>{
                    console.log("========item======", item);
                    if(tenant.value == item.id){
                        this.projectList = item.projects;
                        return true
                    }
                })
            },
        	getProjectInfo(id){
        		this.projectList.some(item =>{
                    if(item.id === id){
                    	console.log("============",item);
                    	item.create_time = 0;
                    	item.end_time = 0;
                        this.object.project = item;
                        return true;
                    }
                })
        	},
        	getSys(){
				var that = this;
				var url = this.CONFIG.progress_url + '/system-map/for/account';
				ajax.get({
					that: that,
					url: url,
					success: function(data) {
						that.sysList = data;
						console.log("---sysList-------",data);
					}
				})
        	},
        	selectSys(data){
        		console.log("--------treterte--------------",data);
        		this.object.object.sysName = data.label;
        	},
        	selectStartTime(date){
        		console.log("--------selectStartTime--------------",date);
        		if(date === undefined || date === null || date === ""){
        			this.object.object.useStartTime = 0;
        		}else{
        			var date = new Date(date);
        			this.object.object.useStartTime = (date.getTime() / 1000);
        		}
        	},
        	selectEndTime(date){
        		console.log("--------selectEndTime--------------",date);
        		if(date === undefined || date === null || date === ""){
        			this.object.object.useEndTime = 0;
        		}else{
        			var date = new Date(date);
        			this.object.object.useEndTime = (date.getTime() / 1000);
        		}
        	},
            checkIP(data){
                console.log("====data====",data);
                // let ipRegex = /^(?:(?:^|,)(?:[0-9]|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])(?:\.(?:[0-9]|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])){3}){1,3}$/
                let ipRegex = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/

                var ipList = data.split(',');
                for(var i=0;i<ipList.length;i++){
                    if (ipRegex.test(ipList[i]) === false) {
                        console.log("---false");
                        // this.$Message.error('输入IP格式有误，请重新输入！')
                        return false;
                    }
                }
                return true;
            },
        	validate() {
                //console.log("---validate----",this.projectValidate(),this.objectValidate());
        		if(!this.projectValidate()){
        			return false;
        		}else if(!this.objectValidate()){
        			return false;
        		}

        		return true;
        	},
        	getInfo() {
                var object = {};
                object = this.object;
                object.base = {
                    dptName:  this.object.user.department
                }
				// object.object = {
				// 	roleId: this.object.roleId,
				// 	projectId: this.object.projectId
				// }

                object.object.roleId=this.object.roleId;
                object.object.projectId=this.object.projectId;
                console.log("----getInfo-------",object);
                return object;
        	},
			getHandleParams(handleInfo) {
				handleInfo.reqSubject = this.object.reqSubject
                handleInfo.reqDes = this.object.reqDes
                handleInfo.des = this.object.des
				handleInfo.startTime = 0
				handleInfo.hopeTime = 0
				handleInfo.isEdit = this.isEdit;

				handleInfo.roleId = this.object.roleId;
				handleInfo.projectId = this.object.projectId;

				console.log("aaaa-------->", this.ifedit, this.isEdit == 1)
				handleInfo.isChangeContent = 0;
				if (!this.ifedit) {
					handleInfo.isChangeContent = 1;
				}
				if (this.isEdit == 1) {
					handleInfo.content = this.getInfo()
				}
			},
			getHandleUserParams(opOptions) {
				var param = {}
				param.vari = opOptions
				param.roleId = this.object.roleId;
				param.projectId = this.object.projectId;
				return param
			}
        },

        props: {
            isEdit:{},
            value:{
                dafault:false
            },
            ifedit: {
                type: Boolean,
                default: false,
            },
            reqId: {
                default: null
            },
            draftsId:{
                default: null
            },
            filesList:{},
            processInfo:{},
        },
	    watch: {
	      ifedit(Val) {
            this.getTenants(this.userId);
            //this.selectTenant(this.tenant);
            this.getSys();
	      }
	    }
	}
</script>